package com.hcy.rabbitruntimeapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.hcy.rabbitbasicmodel.model.ReturnResult;
import com.hcy.rabbitruntimeapi.handler.MyWebSocketFrameHandler;
import com.hcy.rabbitruntimeapi.model.dto.WebSocketKey;
import com.hcy.rabbitbasicmodel.common.MyWebSocketMessage;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * @Author huchenying
 * @Description
 * @Date 2021/12/18 0:12
 */
@RestController
@RequestMapping("/driver")
public class DriverOptController {

    private static final Logger logger = LoggerFactory.getLogger(DriverOptController.class);

    @PostMapping("/dispatcherOrder")
    public ReturnResult dispatcherOrder(@RequestBody MyWebSocketMessage myWebSocketMessage) {
        logger.info("dispatcherOrder start param -> {}", ToStringBuilder.reflectionToString(myWebSocketMessage));
        String res = JSONObject.toJSONString(myWebSocketMessage);

        try {
            WebSocketKey webSocketKey = new WebSocketKey(myWebSocketMessage.getUsername(), myWebSocketMessage.getClientId());
            Channel channel = MyWebSocketFrameHandler.channels.get(webSocketKey);
            if(channel == null){
                throw new RuntimeException("channel is null!");
            }
            channel.writeAndFlush(new TextWebSocketFrame(res));
        } catch (Exception e) {
            logger.error("发送失败 reason -> {}",e.getMessage());
            return ReturnResult.exception("未找到客户端，发送失败！");
        }
        return ReturnResult.success("OK!");
    }
}
